﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// ⚠️ CRITICAL: Adding FBroSharp namespaces
using FBroSharp;                 // ⚠️ #1 MOST CRITICAL! FBroSharpControl, FBroSharpBrowserListControl - ALWAYS FIRST!
using FBroSharp.Const;           // ⚠️ REQUIRED! FBroSharpTransitionType, FBroSharpWindowOpenDisposition
using FBroSharp.DataType;        // ⚠️ REQUIRED! FBroSharpEventDisableControl (struct!)
using FBroSharp.Event;           // ⚠️ REQUIRED! FBroSharpBrowserEvent, FBroInitEvent
using FBroSharp.Lib;             // ⚠️ CRITICAL! IFBroSharpBrowser, IFBroSharpFrame, IFBroSharpUseExtraData
using FBroSharp.Value;           // ⚠️ CRITICAL! IFBroSharpDictionaryValue, FBroSharpWindowsInfo, FBroSharpBrowserSetting
using FBroSharp.Callback;        // ⚠️ REQUIRED! Callback function types

namespace 简单浏览器
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "main_browser";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CreateBrowser();
        }

        private void CreateBrowser()
        {
            try
            {
                // 创建窗口信息
                FBroSharpWindowsInfo windows_info = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // 嵌入到panelBrowser控件中
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "FBro Browser"
                };

                // 创建浏览器事件回调类
                BrowserEvent browser_event = new BrowserEvent(this);

                // 创建浏览器
                if (FBroSharpControl.CreatBrowser(
                    "about:blank",
                    windows_info,
                    default,
                    default,
                    default,
                    browser_event,
                    default,  // ⚠️ 使用 default 而不是 null (struct value type)
                    BROWSER_USER_FLAG))
                {
                    UpdateStatus("浏览器创建成功");
                }
                else
                {
                    UpdateStatus("浏览器创建失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus($"创建失败: {ex.Message}");
            }
        }

        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateStatus), message);
                return;
            }
            lblStatus.Text = message;
        }

        public void UpdateUrl(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateUrl), url);
                return;
            }
            txtUrl.Text = url;
        }

        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateTitle), title);
                return;
            }
            this.Text = title;
        }

        public void UpdateNavigationButtons(bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<bool, bool>(UpdateNavigationButtons), canGoBack, canGoForward);
                return;
            }
            btnBack.Enabled = canGoBack;
            btnForward.Enabled = canGoForward;
        }

        public void UpdateNavigationButtons()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    bool canGoBack = browser.CanGoBack();
                    bool canGoForward = browser.CanGoForward();
                    UpdateNavigationButtons(canGoBack, canGoForward);
                }
                else
                {
                    UpdateNavigationButtons(false, false);
                }
            }
            catch
            {
                UpdateNavigationButtons(false, false);
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            NavigateToUrl(txtUrl.Text);
        }

        private void NavigateToUrl(string url)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    // 确保URL格式正确
                    if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("file://"))
                    {
                        url = "http://" + url;
                    }
                    
                    browser.GetMainFrame().LoadURL(url);
                    UpdateStatus($"正在导航到: {url}");
                }
                else
                {
                    UpdateStatus("浏览器未就绪");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus($"导航失败: {ex.Message}");
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid && browser.CanGoBack())
                {
                    browser.GoBack();
                    UpdateStatus("后退");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"后退失败: {ex.Message}");
            }
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid && browser.CanGoForward())
                {
                    browser.GoForward();
                    UpdateStatus("前进");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"前进失败: {ex.Message}");
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.Reload();
                    UpdateStatus("刷新页面");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"刷新失败: {ex.Message}");
            }
        }

        private void txtUrl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                btnGo_Click(sender, e);
                e.Handled = true;
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void panelBrowser_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    // 调整浏览器大小以匹配容器
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }
    }
}